package com.random;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 奖品有数量的权重测试(数量不影响结果)
 * @author yaojinshan
 *
 */
public class TestPrize2 {
	static List<Prize> pList = new ArrayList<Prize>();//初始化奖品列表
	static int prize_times = 100000;
	static int totalWeight = 0;
	static Map<Integer,QuJian> quJianMap = new HashMap<Integer, QuJian>();
	static double max_random = 0.0d;
	static double min_random = 1.0d;
	static {
		initData();//初始化数据大小
		totalWeight = getTotalWeight();
		Collections.sort(pList);
		computeQuanZhong();
	}

	public static void main(String[] args) {
		int[] result = new int[pList.size()];//结果集
		System.out.println("本次实验次数：" + prize_times);
		int temp;
		for (int i = 0; i < prize_times; i++) {
			temp = compute();
			if(temp != -1){
				result[temp] = result[temp] + 1;
			}
		}
		for(Integer in : quJianMap.keySet()){
			System.out.println("权重概率区间：" + quJianMap.get(in).getQujianValue() + ",出现次数:" + result[in] + ",实验概率：" + (double)result[in] / prize_times);
		}
		System.out.printf("最小随机数：%12.8f \t", min_random);
		System.out.printf("最大随机数：%12.8f", max_random);
	}
	
	public static int compute(){
		double random = Math.random();
		if(max_random < random){
			max_random = random;
		}
		if(min_random > random){
			min_random = random;
		}
		for(Integer in : quJianMap.keySet()){
			QuJian quJian = quJianMap.get(in);
			if(quJian.getMin() <= random && random < quJian.getMax()){
				return in;
			}
		}
		return -1;
	}
	/**
	 * 计算权重区间值
	 */
	public static void computeQuanZhong(){
		double start = 0.0d;
		double end = 0.0d;
		//计算 各个奖品中奖概率
		for (int j = 0 ; j < pList.size();j++) {
			if(j != 0){
				start += ((double)pList.get(j-1).getPrize_weight()) / totalWeight;//累计算出来当前概率区间起始值
			}
			end =  ((double)pList.get(j).getPrize_weight()) / totalWeight;
			quJianMap.put(j, new QuJian(start,start+end));
		}
		System.out.println("权重的概率区间：" + quJianMap);
	}
	/**
	 * 计算总权重
	 * @return
	 */
	public static int getTotalWeight() {
		int total_weight = 0;
		for(Prize prize : pList){
			total_weight += prize.getPrize_weight();
		}
		return total_weight;
	}
	
	/**
	 * 初始化数据大小
	 */
	public static void initData() {
		Prize prize1 = new Prize(1, "奖品1", 30, 10);
		Prize prize2 = new Prize(2, "奖品2", 40, 20);
		Prize prize3 = new Prize(3, "奖品3", 10, 30);
		Prize prize4 = new Prize(4, "奖品4", 20, 40);
		Prize prize5 = new Prize(5, "谢谢参与", -1, 900);
		pList.add(prize1);
		pList.add(prize2);
		pList.add(prize3);
		pList.add(prize4);
		pList.add(prize5);
	}
}
